﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.Xna.Framework.Content.Pipeline;

namespace CrateManiaPipeline
{
    /// <summary>
    /// Represents a layer for a tile map
    /// </summary>
    public class TileMapLayerContent
    {
        /// <summary>
        /// Is the layer visible
        /// </summary>
        public bool IsVisible = true;
        /// <summary>
        /// Layer name (mostly for debug purposes)
        /// </summary>
        public string Name;

        /// <summary>
        /// Layer height (in tiles unit)
        /// </summary>
        public int Width;

        /// <summary>
        /// Layer width (in tiles unit)
        /// </summary>
        public int Height;

        /// <summary>
        /// Set of tiles
        /// </summary>
        /// <remarks>
        /// Key is tile id in image space, value is tileid in tileset space
        /// </remarks>
        public List<KeyValuePair<int,int>> Tiles = new List<KeyValuePair<int,int>>();

        public TileMapLayerContent(XmlNode layerNode, ContentImporterContext context)
        {
            Name = layerNode.Attributes["name"].InnerText;
            Width = int.Parse(layerNode.Attributes["width"].InnerText);
            Height = int.Parse(layerNode.Attributes["height"].InnerText);
            XmlAttribute visibleAttribute = layerNode.Attributes["visible"];
            if (visibleAttribute != null)
                IsVisible = (visibleAttribute.InnerText != "0");

            int tid = 0;
            foreach (XmlNode tile in layerNode.SelectNodes(".//tile"))
            {
                int tilesetTileId = int.Parse(tile.Attributes["gid"].InnerText) - 1;
                // is it a valid tile?
                if ( tilesetTileId >= 0 )
                    Tiles.Add(new KeyValuePair<int, int>(tid, tilesetTileId));
                tid++;
            }
#if DEBUG
            context.Logger.LogImportantMessage("Layer: {0}", new object[] { Name });
            foreach (KeyValuePair<int, int> it in Tiles)
                context.Logger.LogImportantMessage("{0}:{1}", new object[] { it.Key, it.Value });
#endif
        }
    }
}
